DM_Combo = Ext.define('DM_Combo', {
    extend: 'Ext.data.Model',
    fields: [
        'id',
        'name'
    ]
});

var BView = Class(object, {
    Create: function(cfg){
		this.req={		
			"map" : {
				//"rownum" : 15,
				"pss" : [],
				"cns" : [],
				"hql" : "",
				"start" : 0
			},
			"javaClass" : "java.util.HashMap"
		};    	
		this.funcs = cfg.funcs||{};
		this.handles=cfg.handles;
        this.method = 'G';
        this.SN=cfg.SN||"";
        this.cfg_prop_all=cfg.cfg_prop_all||{};
        this.editor="TextField";
        this.cfg_prop={}||cfg.cfg_prop;
        this.cfg_grid={page:true};
		if(cfg.cfg_grid){
			for(x in cfg.cfg_grid)
			  this.cfg_grid[x]=cfg.cfg_grid[x];
		}
        this.func_title=function(o){
        	if (o&&cfg.func_title)
        		return cfg.func_title(o);
        	else
        		return "详细信息";
        }
        //c4w 2.8
        this.func_setdefault=cfg.func_setdefault;
        var prefix=['A','B','C','D','E','F'];
		if(cfg.req){
	        for(x in cfg.req)
	        	this.req.map[x]=cfg.req[x];
		}
		var pNames=[];
		for(var pn in cfg.cfg_prop){
			pNames[pNames.length]=pn;
			var cpn =cfg.cfg_prop[pn]||{};
		    var cfg_pn={display:cpn.display||pn,hidden:cpn.hidden||false,
			    editor:cpn.editor||this.cfg_prop_all.editor||this.editor,
			    width:cpn.width
		    };
    		
    		var cfg_pn_cfg = {tooltip:cpn.tooltip};
    		//c4w 12.19
    		var cfg_df = this.cfgDefault[cfg_pn.editor];
    		if(cfg_df){
    			for(y in cfg_df){
    				cfg_pn_cfg[y]=cfg_df[y];
    			}
    		}
    		if(cpn.cfg){
    			for(y in cpn.cfg){
    				cfg_pn_cfg[y]=cpn.cfg[y];
    			}
    		}
    		cfg_pn.cfg=cfg_pn_cfg;
    		
    		if(this.cfg_prop_all.cfg){
    			for(y in this.cfg_prop_all.cfg)
    				cfg_pn.cfg[y]=cfg_pn.cfg[y]||this.cfg_prop_all.cfg[y];
    		}
    		//默认类型配置参数的细微修改
    		if(cpn.dcfg){
		  		for(y in cpn.dcfg)
		  		  cfg_pn.cfg[y]=cpn.dcfg[y];
	  		}
	  		cfg_pn.renderer=cpn.renderer||this.renderDefault[cfg_pn.editor];
	  		cfg_pn.width=cfg_pn.width||this.gridWidth[cfg_pn.editor];
    		this.cfg_prop[pn]=cfg_pn;
		}
 		if(this.cfg_grid.propNames)
			this.propNames=this.cfg_grid.propNames;
		else
			this.propNames=pNames;

		this.cfg_detail={func_title:this.func_title(),tabs:[{
			title : "所有字段",
			fset : [{
				legend : "所有字段",
				props :pNames
			}]
		}]};
		if(cfg.cfg_detail){
			for(x in cfg.cfg_detail)
			  this.cfg_detail[x]=cfg.cfg_detail[x];
		}
		if(cfg.child_views){
			this.child_views=cfg.child_views;
		}
 		if(cfg.rel_views){
			this.rel_views=cfg.rel_views;
		}
   },
 gridWidth:{
 	 "DateField":150
 },
  cfgDefault:{
    "TextField":{
		width:300
    },
    "TextArea":{
		width:400,
		height:150
    },
   "DateField":{
		width:300,
		format:'Y-m-d H:i:s'
	 }    	
  },
  renderDefault:{
   "DateField":function (val) {
	   if(typeof val == 'string')
		   return val;
	if (val){
		if(val.time){
			var span_oneday = 24*3600000;
			var dt = new Date();
			dt.setTime(val.time);
			var dt_today = new Date();
			//dt_today.setTime(val.time);
			dt_today.setHours(0);
			dt_today.setMinutes(0);
			dt_today.setSeconds(0);
			dt_today.setMilliseconds(0);
			
			var dt_yesterday = new Date();
			dt_yesterday.setTime(dt_today.getTime()-span_oneday);
			
			//24小时内
			if(val.time>=dt_today.getTime()){
				return Ext.Date.format(dt,'今天 H:i');
			}else if(val.time>=dt_yesterday.getTime()){
				return Ext.Date.format(dt,'昨天 H:i');
			}else return Ext.Date.format(dt,'Y-m-d H:i');
		}else{
			return Ext.Date.format(val,'Y-m-d H:i');
		}
	}else{
		return "";
	}
  },
  "FileField2":function(itxt,r,col,l){
	 if(!itxt) return "";
	 var pos0= itxt.lastIndexOf('\\');
	 if(pos0!=-1){
	 	var url = CFG.app_ctx+"servlet/fu?f="+encodeURI(itxt);
	   return "<a href=\""+url+"\" target=\"_blank\">"+itxt+"</a>";;
	 }
   	 var pos1 = itxt.indexOf('[');
   	 var pos2 = itxt.indexOf(']');
   	 if(pos1==-1 || pos2==-1)
   	   return "";
   	 pos2 = itxt.lastIndexOf('~',pos2);
   	 var sp = itxt.substring(pos1+1,pos2).replace(/~/g,'/');
   	 var suffix = col.data.suffix;
   	 var spec = col.data.spec;
   	 if(spec&&spec.trim()!='')
   	   sp=spec+'/'+sp;
   	 if(suffix&&suffix.trim()!='')
   	   sp=suffix+'/'+sp;
   	   //c4w for test
   	  var url=CFG.app_ctx+"servlet/fu?f="+itxt;
	 //var url=Bat.Host+"/upload/"+sp+"/"+itxt;
	 return "<a href=\""+url+"\" target=\"_blank\">"+itxt+"</a>";
	}

  },
  render_display:function(val){
	  return val||'';
  },
  render_date:function(val){
	//return "ssss";
	if (val){
		if(val.time){
			var dt = new Date();
			dt.setTime(val.time);
			return dt.format('Y-m-d');
		}else{
			return val.format('Y-m-d');
		}
	}else{
		return "";
	}
   },
  get_attach_url:function(itxt){
  	return CFG.app_ctx+"servlet/fu?f="+encodeURI(itxt);
  },
  func_cfg_combo:function(data,cfg){
  	var obj = {
		store : new Ext.data.ArrayStore({
			fields : ['txt', 'val'],
			data :data
		}),
		displayField : 'txt',
		valueField : 'val',
		typeAhead : true,
		queryMode : 'local',
		triggerAction : 'all',
		emptyText : '...',
		editable:false,
		selectOnFocus : true//,
		//width:160
	};
	if(cfg){
		for(x in cfg)
		 obj[x]=cfg[x];
	}
	return obj;
  },
  func_cfg_combo_hql:function(hql,vf,cfg_more){ 
	var obj={
	   store:{
	        fields: ['id','name'],
	        proxy: {
	           //异步获取数据，这里的URL可以改为任何动态页面，只要返回JSON数据即可
	            type: 'ajax',
	            url: CFG.app_ctx+'servlet/JSonBaseServlet?hql='+hql,
	            
	            reader: {
	                type: 'array'//,
	                //root: 'list'
	            }
	        },
	        autoLoad: true
	    },
	    queryMode: 'local',
        displayField:'name',
	    valueField:'id',
		emptyText : '...',
		triggerAction: 'all',
	    editable:false,
	    queryCaching :false
	};
	if(cfg_more){
		for(x in cfg_more){
			obj[x]=cfg_more[x];
		}
	}
	return obj;
  }
});

/*
 * 重命名tabs中的属性名
 */
BView.getNextTabProps=function(tabs,shift_step){
	return Bat.clone(tabs,function(pn,pv){
		if(pn!='props' || !pv.pop)
			return pv;
        pv.forEach(function(child, index, array) { 
            pv[index] = BView.getNextPN(child,shift_step);
        });
	});
}

/*
 * 获得合并之后的属性名
 * @param {} pn
 * @return {}
 */
BView.getNextPN=function(pn,shift_step){
	if(pn.length>2){
		var c2 = pn.charAt(1);
		if(c2!='.')
			return String.fromCharCode('A'+shift_step)+pn;
		var c1 = pn.charCodeAt(0);
		var cNext = String.fromCharCode(c1+shift_step);
		return cNext+pn.substring(1); 
	}else return String.fromCharCode('A'+shift_step)+pn;
}
/* 合并流程上下文视图和对象视图，必须考虑对象视图的多表联合查询(多语种)
* @param {} vn1
* @param {} vn2
* @param {} vf
* @return {}
*/
BView.bindView=function(vns,vf){
	var cns=[];
	var pss=[];
	var cfg_prop={};
	var tabs=[];
	var shift_step=0;
	for(var i=0; i<vns.length; i++){
		var vw = BView.viewMap[vns[i]];
		cns = cns.concat(vw.req.cns);
		pss = pss.concat(vw.req.pss);
		for(var x in vw.cfg_prop){
			var px = BView.getNextPN(x,shift_step);
			cfg_prop[px]=vw.cfg_prop[x];
		}
		var tabs_vw = BView.getNextTabProps(vw.cfg_detail.tabs,shift_step);
		tabs.concat(tabs_vw);
		shift_step+=vw.req.cns.length;
	}
//	vw1.req.map.psMap.map.hql=vw2.req.map.psMap.map.hql;
//	vw1.relviews = vw2.relviews;
//	vw1.req.map.psMap.map.SN='AvensHandle';
	var vwr = {
			req:{
				pss:pss,
				cns:cns,
				hql:''
			},
			cfg_prop:cfg_prop,
			cfg_detail:{
				tabs:tabs,
				btns:[]
			},
			cfg_grid:{
				btns:[]
			}
	};
	if(vf) vf(vwr);
	return vwr;
}

BView.getDisplay=function(vn,pn){
	var bv = BView.viewMap[vn]
	if(!bv)
		return pn;
	var cfp = bv.cfg_prop||{};
	var cf= cfp[pn]||{};
	return cf.display||pn;
}

BView.renderSync=function(jsonstr,vn){
	if(!jsonstr)
		return "";
	try{
		var rcs = eval(jsonstr);
		var sbuf = "<table class=\"hor-minimalist-b\" style=\"width:950px;\"><tr><th width='150px' nowrap>指标项</th><th width='400px'>旧值</th><th width='400px' >新值</th></tr>";
		for(var i=0; i<rcs.length; i++){
			var rc=rcs[i];
			var oldValue=rc[1];
			var newValue=rc[2];
			if(oldValue==null)
			    oldValue='';
			if(newValue==null)
			    newValue='';
			
			//   oldValue=oldValue.fromat("yyyy-MM-dd");
			sbuf+="<tr><td nowrap>"+BView.getDisplay(vn,rc[0])
				+"</td><td style='word-break: break-all'>"+oldValue+"</td><td style='word-break: break-all'>"+newValue+"</td><td></tr>";
		}
		sbuf+="</table>";
		return sbuf;
	}catch(e){
		return jsonstr;
	}
}
BView.cfg_status1={
	        editor:'ComboBox',
	        display:"使用状态",
	        width:100,
	        cfg:{
		        displayField : 'txt',
		        editable:false,
				valueField : 'val',
				typeAhead : true,
				queryMode : 'local',
				triggerAction : 'all',				
				selectOnFocus : true,
		    	listConfig: {
				        getInnerTpl: function() {
				            return '<div data-qtip="{txt}">{style} {txt}</div>';
				        }
				},
				store : new Ext.data.ArrayStore({
					fields :['txt', 'val'],
					data :[['使用',1],['停用',0]]
				})
	        },
			renderer : function(val) {	
	           	  var dtxt = {						
					'1':'<font style="color:green;font-size:13px">使用</font>',	
					'0':'<font style="color:red;font-size:13px">停用</font>'};
					return dtxt[val];
	       }
	};
BView.cfg_status={
	 display:"状态",
		editor : 'ComboBox',
		renderer : function(val) {				
		  var dtxt = {						
			'0':'禁用',	
			'1':'启用'};
			return dtxt[val];
		},
		cfg :BView.func_cfg_combo([['启用', 1], ['禁用', 0]])
	};
	BView.device_status={
	 display:"状态",
		editor : 'ComboBox',
		renderer : function(val) {				
		  var dtxt = {						
			'0':'断开',	
			'1':'连接中'};
			return dtxt[val];
		},
		cfg :BView.func_cfg_combo([['断开', 1], ['连接中', 0]])
	};
//负责处理所有留言发送
BView.ChatItems={to:{
    	fieldLabel:'发送到',
    	name:'to',
    	width:400
    },sendToGroup:{
		fieldLabel:'发送到',
		mode:'local',
		name:'sendToGroup',
		xtype:'combo',
		lazyInit:false,
		emptyText :'请选择',
		displayField:'name',
		valueField :'id',
		triggerAction:'all',
		typeAhead :true,
    	store:{
	        fields: ['id','name'],
	        proxy: {
	           //异步获取数据，这里的URL可以改为任何动态页面，只要返回JSON数据即可
	            type: 'ajax',
	            url: CFG.app_ctx+'servlet/JSonBaseServlet?hql=select id,name from UGroup order by id',	            
	            reader: {
	                type: 'array'//,
	               // root: 'list'
	            }
	        },
	        autoLoad: false
	    }},
		mid:{
		fieldLabel:'回复留言',
		name:'mid',
		width:400
	},title:{
		fieldLabel:'题名',
		name:'title',
		width:400
	},content:{
		fieldLabel: '正文',
		name: 'content',
		xtype: 'textarea',
		width:400,
		height:120
	},offline:{
		fieldLabel: '离线发送',
		name: 'offline',
		xtype: 'checkbox'
		//,hidden: true
}};
BView.showDataSet=function(dlg_name,type,btn,bsel){
	var ui=BView.getUi(btn);
	var sids;

	if(!ui){
		bsel=true;
		var ap = layout.tabPanel.getActiveTab();
		var ui = ap.uiDetail;
		var objcur=ui.obj_detail;
		sids=[objcur.items.map['id']||objcur.items.map['B.id']];
	}else if(bsel){
	 	var sels = BView.getSels(btn);
		if(!sels || sels.length==0){
		  Ext.MessageBox.show({
	           title: '系统提示',
	           msg: '请选择条目',
	           buttons: Ext.MessageBox.OK,
	           icon: Ext.MessageBox.INFO
	      });
			return false;
		}
		sids=[];			
		for(var i=0; i<sels.length; i++){
			sids[sids.length]=sels[i].obj.items.map['id']||sels[i].obj.items.map['A.personId'];
		}
	}
	var wp = Bat.dlgs[dlg_name];
	if(!wp){
		Ext.tip.QuickTipManager.init();
        var form = Ext.widget('form', {
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            border: false,
            bodyPadding: 10,

            fieldDefaults: {
                labelAlign: 'top',
                labelWidth: 100,
                width: 250,
                labelStyle: 'font-weight:bold'
            },
            items: [{
                fieldLabel: '',
                labelStyle: 'font-weight:bold;padding:0;',
                layout: 'vbox',
                defaultType: 'textfield',
                items: [{
                    flex: 2,
                    name: 'ds_exist',
                    //afterLabelTextTpl: required,
                    msgTarget :'under',
                    fieldLabel: '添加到<font style="color:red;font-size:13px">现有</font>数据集',
                    valueField:'id',
                    xtype:'combobox',
                    lazyInit:false,
		           	emptyText :'请选择',
		           	displayField:'name',
		           	triggerAction:'all',
		           	typeAhead :true,
		           	minChars:1,
		           	queryCaching :false,
		           	validator:function(val){
		           		if(val){
                    		var fm = this.up('form');
                    		var fld_ds_new = fm.getForm().findField('ds_new');	
                    		fld_ds_new.clearInvalid();
		           		}
		           		return true;
		           	},
		           	listConfig: {
					        getInnerTpl: function() {
					            return '<div data-qtip="{name}">{name} [{total}]</div>';
					        }
					    },
		           	store:{
					        fields: ['id','name','total'],
					        proxy: {
					           //异步获取数据，这里的URL可以改为任何动态页面，只要返回JSON数据即可
					            type: 'ajax',
					            url: CFG.app_ctx+"servlet/JSonBaseServlet?hql=select id,datasetname,total from PinDataset where username='"
					            	+layout.usr_info.user+"'",
					            
					            reader: {
					                type: 'array',
					                root: 'list'
					            }
					        },
					        autoLoad: true
					    }
                },{
                    flex: 2,
                    name: 'ds_new',
                    //afterLabelTextTpl: required,
                    fieldLabel: '添加到<font style="color:red;font-size:13px">新建</font>数据集',
                    msgTarget :'side',
                    validator:function(val){
                    	var fm = this.up('form');
                    	var fld_ds_exist = fm.getForm().findField('ds_exist');
                    	var val_ds_exist = fld_ds_exist.getValue();
                    	if(val_ds_exist)
                    		return true;
                    	if(!val || val.trim()=="")
                    		return "数据集名称不能为空";
                    	else if(val.length>25)
                    		return "名称长度不能大于25个汉字"
    			      	var hql ="from dao.hb.PinDataset where  datasetname='"+val+"'";
    		            var req={"map":{hql:hql},"javaClass":"java.util.HashMap"};
    		            var data = jsonrpc.BH.handle('C',req,'HDDefault');  
    		            if(data==0)
    		            	return true;
    		            else
    		            	return "存在重复的数据集名";
                    },
                    margins: '0 0 0 5'
                }]
            }],
            defaultButton:'appendto_id_ok',
            buttons: [{
                text: '取消',
                handler: function() {
                    this.up('form').getForm().reset();
                    this.up('window').hide();
                }
            }, {
                text: '确定',
                id:'appendto_id_ok',
                handler: function(btn) {
                	var fm = btn.up('form');
                	if(!fm.isValid())
            			return;
                	var rm = fm.getValues();
                	rm.type=fm.type;
                	rm.total = fm.total;
                	if(fm.bsel){
                		rm.sids=fm.sids;
                	}else{
                		rm.filter=fm.filter;
                	}
	                var req={"map":rm,"javaClass":"java.util.HashMap"};
			        fm.getForm().reset();
			        this.up('window').hide();
			        //查重时间可能比较长
			        if(rm.ds_exist && rm.ds_exist!="" && !fm.bsel){
			        	Ext.MessageBox.show({ msg:'正在进行逐条查重和添加，请耐心等待...',title:'系统提示',
	    					modal:true,wait:true,closable:false});
			        }
			       jsonrpc.BH.handle(function(data,ex){
				   		if(Bat.outputEx(ex,'用户退出异常'))
				   			return;		
				        var info = "共导入"+data[1]+"条数据到《"+data[3]+"》,<br>是否转到该数据集？"
				        Ext.MessageBox.confirm("添加成功",info, function(btn){
	                	  if(btn=="no")
		    		 			return;
	                	  layout.renderDetailByKey('dao.hb.PinDataset','id',data[2],{id:"招聘管理",path:"数据集"})
	                   });
					},'A',req,'ZpService');
                }
            }]
        });

        wp = Ext.widget('window', {
            closeAction: 'hide',
            width: 300,
            height: 200,
            layout: 'fit',
            resizable: false,
            modal: true,
            items: form,
        listeners: {
            afterRender: function(thisForm, options){
                this.keyNav = Ext.create('Ext.util.KeyNav', this.el, {                    
                    enter: function(){
                    	var btn_ok = wp.down('button[id=appendto_id_ok]');
                    	btn_ok.handler.call(btn_ok.scope || btn_ok, btn_ok); 
                    	//console.log(btn_ok);
                    },
                    scope: this
                });
            }
        }
        });
        Bat.dlgs[dlg_name]=wp;
    }
    var fm = wp.down('form');
    fm.ui = ui;
    fm.bsel=bsel;
    var dlg_title;
    if(bsel){
        fm.sids=sids;
        fm.total = sids.length;
        fm.type=type;
    	dlg_title = "添加选中的【"+fm.total+"】条到数据集";
    }else{
    	fm.filter = ui.getreq();
    	fm.total = ui.total;
    	fm.type=type;
    	dlg_title = "添加检索结果【"+fm.total+"】条到数据集";
    }
    var fld_ds_exist = fm.getForm().findField('ds_exist');
    //c4w 2015 扩大增加到现有数据集的最大数目到200
    //if(fm.total>99){
    if(fm.total>200){
    	fld_ds_exist.disable();
    }else{
    	fld_ds_exist.enable();
    }
	wp.setTitle(dlg_title);
	wp.show({animateTarget :btn.getEl()});	
	fm.isValid();
}
BView.sendMessage=function(dlg_name,dlg_title,flds_show,flds_hide,func_succ){
	var wp = Bat.dlgs[dlg_name];
	if(!wp){
		var its = [];
		for(var x in flds_show){
			var ci=BView.ChatItems[x];
			ci.value=flds_show[x];
			its[its.length]=ci;
		}
	    var fm = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 80,
        items: [{
            xtype:'fieldset',
            width:"100%",
            autoHeight:true,
            title: '',
             defaultType: 'textfield',
            items:its}]        
    });
    wp = new Ext.Window({
    	closeAction:'hide',
    	shadow: true,
        title: '发送留言',
        width: 450,
        autoHeight:true,
        layout: 'form',
        plain:true,
        bodyStyle:'padding:5px;',
        buttonAlign:'center',
        items: fm,
		defaultButton:'id_ok',
        buttons: [{
        	//id:'id_ok',
            text: '确定',
            handler: function(){
            	var ps = fm.getForm().getValues();   
            	var ctl_sendToGroup=fm.getForm().findField('sendToGroup');
            	if(ctl_sendToGroup){
            		ps.sendToGroupId = ctl_sendToGroup.getValue();
            		if(!ps.sendToGroupId || ps.sendToGroupId=="")
            			return;            			
            	}
            	//加上隐藏的字段值
            	var flds_hide=wp.flds_hide;
            	if(flds_hide){
            	  for(x in flds_hide)
            		ps[x]=flds_hide[x];
            	}
             	var req={"map":ps,"javaClass":"java.util.HashMap"};
			  jsonrpc.BH.handle(function(data,ex){
		   		if(Bat.outputEx(ex,'发送留言异常'))
		   			return;
		   		if(wp.func_succ)
		   			wp.func_succ();
		   		layout.selectNode("留言","已发送");
			  	wp.hide();
			  },'M',req,'UMService'); 
            }            
        },{
            text: '取消',
            handler: function(){
            	wp.hide();
            }
        }],
        keys: [
        //回车确定
         /*   {stopEvent: true,
			 key: [Ext.EventObject.ENTER], handler: function() {
            	var btn_ok=wp.buttons[0];
            	btn_ok.handler.call(btn_ok.scope || btn_ok, btn_ok); 
               }
            }*/
        ]        
    });
	Bat.dlgs[dlg_name]=wp;
	}
	var fld_its = wp.items.items[0].items.items[0].items;
	var pos=0;
	//每次重新赋值
    wp.flds_hide=flds_hide;
    if(func_succ)
    	wp.func_succ=func_succ;
	for(var x in flds_show){
		fld_its.items[pos].setValue(flds_show[x]);
		pos++;
	}

	wp.setTitle(dlg_title);
	wp.show();	
}
BView.getUi=function(btn){
	var grid=btn.up('bat_grid');
	if(grid)
		return grid.ui;
	else
		return false;
}
BView.getSels=function(btn){
	//var ui=btn.ui;
	var sels=btn.up('bat_grid').getSelectionModel().getSelection();
	return sels;
}
BView.getSelObj=function(btn){
	
	var sels=btn.up('bat_grid').getSelectionModel().getSelection();
	if(sels && sels.length>0){
		return sels[0].obj
	}else return null;
}
BView.expandFieldSet=function(editors,fns,obj){
	for(var i=0; i<fns.length; i++){
		var fn = fns[i];
		var ed = editors[fn][0];
		var fs = ed.up('fieldset');
		if(fs){
			var ed_val = obj.items.map[fn];
			if(ed_val && ed_val.trim()!="")
				fs.expand();
			else
				fs.collapse(); 
		}
	}
}
BView.setEnableFields=function(editors,fns,b_enable, b_other){
	for(var x in editors){
		var hit=false;
		for(var i=0; i<fns.length; i++){
			if(fns[i]==x){
				hit=true;
				break;
			}
		}
		var flds=editors[x];
		for(var i=0; i<flds.length; i++){
			if(hit){
				flds[i].readOnlyCls='form_date_readonly';
				flds[i].setReadOnly(b_enable);
				flds[i].b_readonly = b_enable;
			}
			else if(!b_other){
				flds[i].setReadOnly(!b_enable);
				flds[i].b_readonly = !b_enable;
			}
		}
	}
}
BView.openTabpanel=function(id,title,url){
	BView.tabs = BView.tabs||{};
	var tab=BView.tabs[id];
	var tabPanel = layout.tabPanel;
	 var id_frm = "ifrm_"+id;
	if(!tab){
	 tab = tabPanel.add({
		bodyStyle:'padding:10px;font-size:12px;',
        title: title,
        iconCls: 'tabs',
        html: "<iframe style=\"border: 0px;\" width=\"100%\" height=\"100%\" id=\""+id_frm+"\"></iframe>",
       	closable:true,
        autoDestroy: false,
		autoScroll: true,
		bHide:true
     }).show();
     BView.tabs[id]=tab;
     //tab.show();
	}else{
		tab.bHide=false;
		//tabPanel.unhideTabStripItem(tab);
		tab.setTitle(title);
		tab.tab.show();
		tabPanel.setActiveTab(tab);
	}
	Ext.get(id_frm).dom.src=url;
}
BView.getBtnForExcel= function(cfg){
	cfg.baseURL =CFG.app_ctx+"servlet/DefaultExportExcelControl?obj="+cfg.obj; 
	var single={
   	   text: '导出选择的记录(Excel)',
	   iconCls: 'plugin_add',
	   handler : function(btn){
	   	   var sels=BView.getSels(btn);
		   if(!sels) return;
		   var selid="";
		   for(var i=0; i<sels.length; i++){
		   	 var o = sels[i].obj;
		   	 if(i==0)
		   		selid =o.items.map[cfg.id];
		   	 else
		   	 	selid =selid+','+o.items.map[cfg.id];
		   }
		   var url = cfg.baseURL+"&sid="+selid+"&type=S";
		   window.open(url,'_blank');
		   return false;
       }
   }
    var currentPage={
		text: '导出当前页的所有记录(Excel)',
		//iconCls: 'plugin_add',
		handler : function(btn){
			var ui=BView.getUi(btn);
  			var id_="";
  			var selid="";
  			for(var i=0,len=ui.objs.length; i<len; i++){
				var obj=ui.objs[i];
				if (obj.action!='D'){
					var it=obj.items.map||{};
					id_ = it[cfg.id];
					selid = selid + id_ + ',';
			    }
            }
		    var url = cfg.baseURL+"&sid="+selid+"&type=P";
	    	window.open(url,'_blank');
        }
    }
	var all={
   		text: '导出所有记录(Excel)',
   		//iconCls: 'plugin_add',
		handler : function(btn){
			var url = cfg.baseURL+"&type=A";
			window.open(url,'_blank');
	    }
    };
    var filter={
   	       text: '根据过滤条件导出(Excel)',
   		   //iconCls: 'plugin_add',
		   handler : function(btn){
		       var ui=BView.getUi(btn);
			   var url = cfg.baseURL+"&type=F&filter="+encodeURIComponent(ui.getreq());
			   window.open(url,'_blank');
		   }
	   }
	return 	{
		text: '导出',
		cls: 'x-btn-text-icon',
		icon: 'icons/page_excel.png',				
		menu:{
			items:eval(cfg.item)
	    }
	}
};
BView.getBtnForWord= function(cfg){
	cfg.baseURL =CFG.app_ctx+"servlet/exportWord?obj="+cfg.obj; 
	var single={
   	   text: '导出选择的记录(Word)',
	   iconCls: 'plugin_add',
	   handler : function(btn){
	   	   var sels=btn.ui.grid.getSelectionModel().getSelections();
		   if(!sels) return;
		   var selid="";
		   for(var i=0; i<sels.length; i++){
		   	 var o = sels[i].obj;
		   	 if(i==0)
		   		selid =o.items.map[cfg.id];
		   	 else
		   	 	selid =selid+','+o.items.map[cfg.id];
		   }
		   var url = cfg.baseURL+"&sid="+selid+"&type=S";
		   window.open(url,'_blank');
		   return false;
       }
   };
    var filter={
   	       text: '根据过滤条件导出(Word)',
   		   //iconCls: 'plugin_add',
		   handler : function(btn){
		       var ui=btn.ui;
			   var url = cfg.baseURL+"&type=F&filter="+encodeURIComponent(ui.getreq());
			   window.open(url,'_blank');
		   }
	   }
	return 	{
		text: '导出',
		cls: 'x-btn-text-icon',
		icon: 'icons/page_excel.png',				
		menu:{
			items:eval(cfg.item)
	    }
	}
}
BView.print = function(ct){
	var mywindow = window.open('_blank', 'my div', 'height=800,width=1000');
    mywindow.document.write('<html><head><title>my div</title>');
    /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
    mywindow.document.write('</head><body >');
    mywindow.document.write(ct);
    mywindow.document.write('</body></html>');

    mywindow.print();
    mywindow.close();
}
BView.getBtnChart=function(ui,ths){
	var grpItems = [];
	for (var h = 0, hlen = ths.length; h < hlen; h++) {
		grpItems[grpItems.length] = new Ext.menu.CheckItem({
			text : ths[h][1],
			checked : false,
			group : 'grp',
			scope : ui,
			prop : ths[h][0],
			handler : function(item, evtObj) {
				this.grpbtn.prop = item.prop;
				//this.ordbtn.setText(Bat.ORDBYDIS);
			}
		});
	}
	var grpbtn = new Ext.Button({
		text : "图表",
		cls : 'x-btn-text-icon',
		icon : 'icons/chart_pie.png',
		menu : new Ext.menu.Menu({
			items : [{
				name:"统计数目",
				xtype : "combo",
				store : new Ext.data.SimpleStore({
					fields : ['txt', 'val'],
					data : [[+10, +10], [+50, +50],
							[+100, +100], [-10, -10],
							[-50, -50], [-100, -100]]
				}),
				displayField : 'txt',
				valueField : 'val',
				typeAhead : true,
				mode : 'local',
				triggerAction : 'all',
				emptyText : 'Top...',
				selectOnFocus : true,
				width : 135,
				value : 10
			}, new Ext.menu.CheckItem({
				text : '分组字段',
				group : 'grp',
				menu : {
					items : grpItems
				}
			}), {
				text : "数据报表",
				scope : ui,
				handler : function(btn) {
					var filter = this.getreq();
					var pos = filter.toLowerCase().indexOf('order by');
					if(pos!=-1){
						filter = filter.substring(0,pos-1);
					}
					var burl = CFG.app_ctx+"servlet/DefaultExportExcelControl?type=G&filter="
							+ filter
							+ "&obj="
							+ this.view.req.map.cns[0]
							+ "&group="
							+ this.grpbtn.prop
							+ "&top="
							+ this.grpbtn.menu.items.items[0]
									.getValue();
					// alert(burl);
					window.open(burl);
				}
			}, {
				text : "饼状图",
				scope : ui,
				handler : function(btn) {
					btn.parentMenu.hide();
					var group = this.grpbtn.prop + "";
					var top = this.grpbtn.menu.items.items[0].getValue();
					var filter = this.getreq();
					var pos = filter.toLowerCase().indexOf('order by');
					if(pos!=-1){
						filter = filter.substring(0,pos-1);
					}
					burl = CFG.app_ctx+"servlet/GenerateReportFormServlet?type=G&filter="
							+ filter
							+ "&obj="
							+ this.view.req.map.cns[0]
							+ "&group="
							+ this.grpbtn.prop
							+ "&top="
							+ this.grpbtn.menu.items.items[0].getValue() + "&chart=P";
					if (group == "undefined") {
						Ext.MessageBox.alert("提示",
								"进行统计分析前，请先选择分组字段 。");
						return false;
					}
					if (!this["panel_Pie"]) {
						this.getPanel("Pie", "饼状图", [{
							text : '环状图',
							cls : 'x-btn-text-icon',
							icon : 'icons/email_go.png',
							enableToggle : true, 
							toggleHandler : function(btn,pressed) {
								var chart = this.pieChart;
								chart.series.first().donut = pressed? 35: false;
								chart.refresh();
							}
						}, {
							text : '打印',
							cls : 'x-btn-text-icon',
							icon : 'icons/email_link.png',
							handler : function(btn) {
								//Ext.override(Ext.draw.engine.ImageExporter, { defaultUrl:CFG.app_ctx+"servlet/svg"});
								var svgdata = Ext.draw.engine.SvgExporter.generate(this.pieChart.surface);
								BView.print(svgdata);
							}
						}]);
					} else {
						var panel_Pie=this["panel_Pie"];
						panel_Pie.tab.show();
						panel_Pie.bHide = false;
						this.tabPanel.setActiveTab(panel_Pie);
					}
					BView.renderPie(this,this["panel_div_Pie"], burl,group);
					return false;
				}
			}, {
				text : "柱状图",
				scope : ui,
				handler : function(btn) {
					btn.parentMenu.hide();
					var group = this.grpbtn.prop + "";
					var filter = this.getreq();
					var pos = filter.toLowerCase().indexOf('order by');
					if(pos!=-1){
						filter = filter.substring(0,pos-1);
					}
					burl = CFG.app_ctx+"servlet/GenerateReportFormServlet?type=G&filter="
							+ filter
							+ "&obj="
							+ this.view.req.map.cns[0]
							+ "&group="
							+ this.grpbtn.prop
							+ "&top="
							+ this.grpbtn.menu.items.items[0].getValue() + "&chart=C";
					if (group == "undefined") {
						Ext.MessageBox.alert("提示",
								"进行统计分析前，请先选择分组字段 。");
						return false;
					}
					if (!this["panel_Column"]) {
						this.getPanel("Column", "柱状图",[{
							text : '打印',
							cls : 'x-btn-text-icon',
							icon : 'icons/email_link.png',
							handler : function(btn) {
								//Ext.override(Ext.draw.engine.ImageExporter, { defaultUrl:CFG.app_ctx+"servlet/svg"});
								var svgdata = Ext.draw.engine.SvgExporter.generate(this.colChart.surface);
								BView.print(svgdata);
							}
						}]);										
					} else {
						var panel_Column=this["panel_Column"];
						panel_Column.tab.show();
						panel_Column.bHide = false;
						this.tabPanel.setActiveTab(panel_Column);
					}
					BView.renderColumn(this,this["panel_div_Column"], burl,group);
				}
			}]
		})
	});
	return grpbtn;
}
BView.renderColumn=function(ui,divId, burl, group) {
	var vw = ui.view;
	var vpd = vw.cfg_prop || {};
	// alert(burl+divId+vpd["taskid"].display);
	var top = ui.grpbtn.menu.items.items[0].getValue();
	var jsonReader = new Ext.data.reader.Json({
		root : "results",
		type : "json"
	});
	var proxy_ajax =  {
		type : "ajax",
		url : burl,
		reader : jsonReader
	};
	var cs;
	var fn_group='name';
	var colChart = ui.colChart;
if(!colChart){
	cs = new Ext.data.Store({
		fields : [fn_group,'Count'],
		proxy :proxy_ajax,
		autoLoad : false
	});
	// 配置柱图颜色及主题
	var colors = ['url(#v-1)', 'url(#v-2)', 'url(#v-3)', 'url(#v-4)',
			'url(#v-5)'];
	for (var i = 0; i < colors.length; i++) {
		colors[i] = colors[i].substr(0, colors[i].length - 1) + '-' + divId+ ')';
	}
	var baseColor = '#171717';
	Ext.define('Ext.chart.theme.Fancy', {
		extend : 'Ext.chart.theme.Base',
		constructor : function(config) {
			this.callParent([Ext.apply({
				axis : {
					fill : baseColor,
					stroke : baseColor
				},
				axisLabelLeft : {
					fill : baseColor
				},
				axisLabelBottom : {
					fill : baseColor
				},
				axisTitleLeft : {
					fill : baseColor
				},
				axisTitleBottom : {
					fill : baseColor
				},
				colors : colors
			}, config)]);
		}
	});
	colChart = Ext.create('Ext.chart.Chart',{
		width : Ext.get(divId).getWidth() * 0.8,
		height : 400,
		xtype : 'chart',
		renderTo : divId,
		theme : 'Fancy',
		animate : {
			easing : 'bounceOut',
			duration : 750
		},
		store : cs,
		background : {
			fill : 'rgb(255, 255, 255)'
		},
		gradients : [{
			'id' : 'v-1-' + divId,
			'angle' : 0,
			stops : {
				0 : {
					color : 'rgb(212, 40, 40)'
				},
				100 : {
					color : 'rgb(117, 14, 14)'
				}
			}
		}, {
			'id' : 'v-2-' + divId,
			'angle' : 0,
			stops : {
				0 : {
					color : 'rgb(180, 216, 42)'
				},
				100 : {
					color : 'rgb(94, 114, 13)'
				}
			}
		}, {
			'id' : 'v-3-' + divId,
			'angle' : 0,
			stops : {
				0 : {
					color : 'rgb(43, 221, 115)'
				},
				100 : {
					color : 'rgb(14, 117, 56)'
				}
			}
		}, {
			'id' : 'v-4-' + divId,
			'angle' : 0,
			stops : {
				0 : {
					color : 'rgb(45, 117, 226)'
				},
				100 : {
					color : 'rgb(14, 56, 117)'
				}
			}
		}, {
			'id' : 'v-5-' + divId,
			'angle' : 0,
			stops : {
				0 : {
					color : 'rgb(187, 45, 222)'
				},
				100 : {
					color : 'rgb(85, 10, 103)'
				}
			}
		}],
		axes : [{
			type : 'Numeric',
			position : 'left',
			fields : ['Count'],
			minimum : 0,
			label : {
				renderer : Ext.util.Format.numberRenderer('0,0')
			},
			title : '总数',
			labelTitle : {
				font : 'bold 12px Arial'
			},
			grid : {
				odd : {
					stroke : '#555'
				},
				even : {
					stroke : '#555'
				}
			}
		}, {
			type : 'Category',
			position : 'bottom',
			fields : [fn_group],
			title : vpd[group].display,
			labelTitle : {
				font : 'bold 12px Arial'
			},// 定义label的字体
			label : {
				rotation : {
					degrees : 0
				}
			}
		}],
		series : [{
			type : 'column',
			axis : 'left',
			highlight : true,
			label : {
				display : 'insideEnd',
				'text-anchor' : 'middle',
				field : 'Count',
				orientation : 'horizontal',
				fill : '#fff',
				font : '12px Arial'
			},
			// 定义鼠标悬停效果
			tips : {
				trackMouse : true,
				height : 60,
				width : 245,
				renderer : function(storeItem, item) {
					var total = 0;
					chartstore.each(function(rec) {
						total += rec.get('Count');
					});
					this.setTitle(vpd[group].display
							+ "："
							+ storeItem.get(fn_group)
							+ "<br>"
							+ "总数："
							+ storeItem.get('Count')
							+ "<br>"
							+ "百分比："
							+ Math.round(storeItem.get('Count') / total
									* 10000) / 100 + '%');
				}
			},
			// 根据颜色配置 对柱子进行颜色填充
			renderer : function(sprite, storeItem, barAttr, i) {
				barAttr.fill = colors[i % colors.length];
				return barAttr;
			},
			style : {
				opacity : 0.95
			},
			xField : group,
			yField : 'Count'
		}]
	});
	ui.colChart=colChart;
}else{
	
	cs = colChart.getStore();
	cs.setProxy(proxy_ajax);
}
	cs.load();
	var info = "<span style='margin:10px;'>根据<strong>"
			+ vpd[group].display + "</strong>进行分组统计，取总数的前<strong>" + top
			+ "</strong>个。</span>";
	colChart.getEl().insertHtml('beforeBegin',info);
	
}

BView.renderPie=function(ui,divId, burl, group) {
	var vw = ui.view;
	var vpd = vw.cfg_prop || {};
	var printFP;
	var fn_group = 'name';
	// alert(burl+divId+vpd["taskid"].display);
	var top = ui.grpbtn.menu.items.items[0].getValue();
	var jsonReader = new Ext.data.reader.Json({
		root : "results",
		type : "json"
	});
	var proxy_ajax =  {
		type : "ajax",
		url : burl,
		reader : jsonReader
	};
	var cs;
	var pieChart = ui.pieChart;
if(!pieChart){
	cs = new Ext.data.Store({
		fields : [fn_group,'Count'],
		proxy :proxy_ajax,
		autoLoad : false
	});
	
	var donut = false;
	 pieChart = Ext.create('Ext.chart.Chart', {
		renderTo : divId,
		flex : 1,
		xtype : 'chart',
		//id : 'pieChart_' + divId,
		layout: 'fit',
		width : Ext.get(divId).getWidth() - 100,
		height : 550,
		animate : true,
		store : cs,
		shadow : true,
        legend: {
            position: 'right'
        },
		insetPadding : 20,
		theme : 'Base:gradients',
		series : [{
			type : 'pie',
			field : 'Count',
			showInLegend : true,
			donut : donut,
			tips : {
				trackMouse : true,
				width : 245,
				height : 60,
				renderer : function(storeItem, item) {
					var total = 0;
					cs.each(function(rec) {
						total += rec.get('Count');
					});
					this.setTitle(vpd[group].display
							+ "："
							+ storeItem.get(fn_group)
							+ "<br>"
							+ "总数："
							+ storeItem.get('Count')
							+ "<br>"
							+ "百分比："
							+ Math.round(storeItem.get('Count') / total
									* 10000) / 100 + '%');
				}
			},
			highlight : {
				segment : {
					margin : 20
				}
			},
			label : {
				field : fn_group,
				display : 'rotate',
				contrast : true,
				font: '18px Arial'
			},
			animate : true
		}]
	});
	ui.pieChart=pieChart;
}else{
	cs = pieChart.getStore();
	cs.setProxy(proxy_ajax);
}
	cs.load();
	var info = "<span style='margin:10px;'>根据<strong>"
			+ vpd[group].display + "</strong>进行分组统计，取总数的前<strong>" + top
			+ "</strong>个。</span>";
	pieChart.getEl().insertHtml('beforeBegin',info);
};
